// pages/orderDetail/orderDetail.js

import {
    numToString
} from '../../utils/util';
import {
    getOrderByOrderIdData
} from '../../api/api';

Page({

    data: {
        storeName: '',
        orderInfo: {},
        totalPaying: 0,
        canvasWidth: 375,
        canvasHeight: 300,
        isGeneratingImage: false,
        shareImageUrl: '',
        authFailed: false, // 权限验证失败标志
        maijiaId: '' // 卖家ID
    },


    onLoad(options = {}) {
        const {
            orderId,
            storeName,
            username = '',
            totalPaying = 0
        } = options;
        const parseStoreName = storeName ? decodeURIComponent(storeName) : '';
        try {
            this.username = decodeURIComponent(username || '');
        } catch (e) {
            this.username = username || '';
        }
        this.setData({
            storeName: parseStoreName,
            totalPaying: Number(totalPaying) || 0
        });
        const targetOrderId = orderId;
        if (!targetOrderId) {
            wx.showToast({
                title: '缺少订单ID',
                icon: 'none'
            });
            return;
        }
        this.orderId = targetOrderId;
        this.fetchOrderDetail(targetOrderId);
    },
    // 统一构造明细信息以维持分享与详情的视觉一致
    normalizeOrderDetail(orderDetail) {
        if (!Array.isArray(orderDetail) || !orderDetail.length) return [];
        if (orderDetail[0]?.table) return orderDetail;
        const newDetail = [];
        orderDetail.forEach(item => {
            let table = [];
            if (item.num) table.push({
                name: '数量:',
                total: item.num,
                unit: '件'
            })
            if (item.weight) table.push({
                name: '重量:',
                total: item.weight,
                unit: item.unit
            })
            if (item.price) table.push({
                name: '单价:',
                total: item.price,
                type: 0,
                unit: item.unit
            })
            if (item.goods_price) table.push({
                name: '货款:',
                total: item.goods_price,
                unit: '元'
            })
            const fujiafeis = Array.isArray(item.order_detail_fujiafei) ? item.order_detail_fujiafei : [];
            fujiafeis.forEach(it => {
                if (it && it.total) table.push({
                    name: (it.name || '') + ':',
                    total: it.total,
                    unit: '元'
                })
            })
            if (table.length % 3) {
                const completion = 3 - table.length % 3;
                for (let index = 0; index < completion; index++) {
                    table.push({})
                }
            }
            newDetail.push({
                goods_name: item.goods_name,
                goods_id: item.goods_id,
                total_price: item.total_price,
                table
            })
        })
        return newDetail;
    },
    // 通过接口兜底刷新订单内容，避免分享链路数据滞后
    async fetchOrderDetail(orderId) {
        if (!orderId) return;
        try {
            const res = await getOrderByOrderIdData({
                order_id: orderId
            }, {
                showLoading: true
            });
            if (res?.code == 403) {
                this.handleNoAuth();
                return;
            }
            const latestData = res?.data || {};
            if (!latestData.id) return;
            const newDetail = this.normalizeOrderDetail(latestData.order_detail);
            const sheqian_price = numToString((latestData.total_price || 0) + (latestData.duoshou || 0) - (latestData.youhui || 0) - (latestData.huan || 0));
            const prevOrderInfo = this.data.orderInfo || {};
            const mergedOrderInfo = {
                ...prevOrderInfo
            };
            if (newDetail.length) mergedOrderInfo.order_detail = newDetail;
            const updatableFields = ['status', 'piao_num', 'add_time', 'huankuan_time', 'pay_time', 'total_price', 'huan', 'youhui', 'duoshou', 'store_id'];
            updatableFields.forEach(key => {
                if (latestData[key] !== undefined && latestData[key] !== null) {
                    mergedOrderInfo[key] = latestData[key];
                }
            });
            if (!isNaN(Number(latestData.total_price)) || !isNaN(Number(latestData.duoshou)) || !isNaN(Number(latestData.youhui)) || !isNaN(Number(latestData.huan))) {
                mergedOrderInfo.sheqian_price = sheqian_price;
            }
            this.setData({
                orderInfo: mergedOrderInfo,
                maijiaId: latestData.maijia_id || this.data.maijiaId
            })
        } catch (error) {
            console.error('获取订单详情失败', error);
        }
    },
    // 权限校验入口
    handleNoAuth() {
        const { orderInfo } = this.data;
        this.setData({ authFailed: true });
        wx.showModal({
            title: '提示',
            content: '身份认证失败，无权查看',
            showCancel: false,
            confirmText: '确定',
            success: (modalRes) => {
                if (modalRes.confirm) {
                    wx.reLaunch({
                        url: `/pages/index/index`,
                    });
                }
            }
        });
    },

    toReconciliation() {
        wx.reLaunch({
            url: `/pages/reconciliation/reconciliation?storeId=${this.data?.orderInfo?.store_id}&storeName=${encodeURIComponent(this.data.storeName)}&username=${encodeURIComponent(this.username)}`,
        })
    },
    // 阻止冒泡，避免点击分享按钮触发父级跳转
    stopTap() { },

    // 格式化日期（精确到秒）
    formatDateWithSeconds(dateStr) {
        if (!dateStr) return '-';
        try {
            const date = new Date(dateStr.replace(/-/g, '/'));
            const pad = (num) => String(num).padStart(2, '0');
            return `${date.getFullYear()
                }-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(
                    date.getHours()
                )}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
        } catch (e) {
            return dateStr;
        }
    },

    // 创建分享图片
    createShareImage() {
        return new Promise((resolve, reject) => {
            const ctx = wx.createCanvasContext('shareCanvas');
            const { canvasWidth, canvasHeight, orderInfo, storeName } = this.data;

            // 设置背景色
            ctx.setFillStyle('#f5fafe');
            ctx.fillRect(0, 0, canvasWidth, canvasHeight);

            // 添加边框
            ctx.setStrokeStyle('#f0f0f0');
            ctx.setLineWidth(1);
            ctx.strokeRect(0, 0, canvasWidth, canvasHeight);

            // 绘制买家名称（标题）- 加粗效果
            ctx.setFillStyle('#000000');
            ctx.setFontSize(36);
            ctx.setTextAlign('left');
            const buyerName = storeName || '商家';
            // 多次绘制模拟加粗
            ctx.fillText(buyerName, 29, 60);
            ctx.fillText(buyerName, 29.5, 60);
            ctx.fillText(buyerName, 29, 60.5);
            ctx.fillText(buyerName, 29.5, 60.5);

            // 绘制副标题 "订单金额" - 字体较大
            ctx.setFillStyle('#999999');
            ctx.setFontSize(24);
            ctx.fillText('订单金额', 30, 100);

            // 绘制订单号 "(单号:xxx)" - 字体较小，并留有间距
            const labelWidth = ctx.measureText('订单金额').width;
            ctx.setFontSize(20);
            ctx.fillText(`（单号:${orderInfo.piao_num || orderInfo.id || ''}）`, 30 + labelWidth + 8, 100);

            // 绘制金额（大号绿色）- 加粗效果
            ctx.setFillStyle('#3abe2c');
            ctx.setFontSize(48);
            ctx.setTextAlign('left');
            const amountText = `¥${numToString(orderInfo.sheqian_price || 0)}`;
            // 多次绘制模拟加粗
            ctx.fillText(amountText, 30, 160);
            ctx.fillText(amountText, 30.5, 160);
            ctx.fillText(amountText, 30, 160.5);
            ctx.fillText(amountText, 30.5, 160.5);

            // 绘制订单时间（精确到秒）
            const orderTime = `订单时间：${this.formatDateWithSeconds(orderInfo.add_time)}`;
            ctx.setFillStyle('#666666');
            ctx.setFontSize(18);
            ctx.fillText(orderTime, 30, 200);

            // 绘制底部绿色渐变按钮区域（带圆角）
            const btnX = 30;
            const btnY = canvasHeight - 70;
            const btnWidth = canvasWidth - 60;
            const btnHeight = 50;
            const btnRadius = 2;

            // 绘制圆角矩形
            ctx.beginPath();
            ctx.moveTo(btnX + btnRadius, btnY);
            ctx.lineTo(btnX + btnWidth - btnRadius, btnY);
            ctx.arcTo(btnX + btnWidth, btnY, btnX + btnWidth, btnY + btnRadius, btnRadius);
            ctx.lineTo(btnX + btnWidth, btnY + btnHeight - btnRadius);
            ctx.arcTo(
                btnX + btnWidth,
                btnY + btnHeight,
                btnX + btnWidth - btnRadius,
                btnY + btnHeight,
                btnRadius
            );
            ctx.lineTo(btnX + btnRadius, btnY + btnHeight);
            ctx.arcTo(btnX, btnY + btnHeight, btnX, btnY + btnHeight - btnRadius, btnRadius);
            ctx.lineTo(btnX, btnY + btnRadius);
            ctx.arcTo(btnX, btnY, btnX + btnRadius, btnY, btnRadius);
            ctx.closePath();

            // 填充渐变色（135度,从青绿到草绿）
            const gradient = ctx.createLinearGradient(btnX, btnY, btnX + btnWidth, btnY + btnHeight);
            gradient.addColorStop(0.2, '#009481'); // 青绿色（20%）
            gradient.addColorStop(1, '#52b316'); // 草绿色（100%）
            ctx.setFillStyle(gradient);
            ctx.fill();

            // 绘制按钮文字
            ctx.setFillStyle('#ffffff');
            ctx.setFontSize(20);
            ctx.setTextAlign('center');
            ctx.fillText('查看订单详情', canvasWidth / 2, btnY + btnHeight / 2 + 6);

            // 绘制完成后，生成图片
            ctx.draw(false, () => {
                setTimeout(() => {
                    wx.canvasToTempFilePath({
                        canvasId: 'shareCanvas',
                        success: (res) => {
                            console.log('分享图片生成成功:', res.tempFilePath);
                            this.setData({
                                shareImageUrl: res.tempFilePath,
                                isGeneratingImage: false
                            });
                            resolve(res.tempFilePath);
                        },
                        fail: (err) => {
                            console.error('生成图片失败:', err);
                            this.setData({
                                isGeneratingImage: false
                            });
                            reject(err);
                        }
                    });
                }, 300);
            });
        });
    },

    // 分享配置
    onShareAppMessage(options) {
        console.log('分享被点击', options);

        // 显示 loading
        wx.showLoading({
            title: '正在生成分享图片...',
            mask: true
        });

        // 标记正在生成
        this.setData({
            isGeneratingImage: true
        });

        // 返回 Promise，异步生成图片
        return this.createShareImage().then(imagePath => {
            wx.hideLoading();
            const sharePath = `/pages/orderDetail/orderDetail?orderId=${this.orderId}&storeName=${encodeURIComponent(this.data.storeName)}&username=${encodeURIComponent(this.username || '')}&totalPaying=${this.data.totalPaying || 0}`;

            return {
                title: `${this.data.storeName || '商家'}`,
                path: sharePath,
                imageUrl: imagePath
            };
        }).catch(error => {
            wx.hideLoading();
            wx.showToast({
                title: '生成图片失败',
                icon: 'none'
            });
            // 返回默认分享内容（留在订单详情页）
            const orderInfoStr = encodeURIComponent(JSON.stringify(this.data.orderInfo || {}));
            return {
                title: '订单分享',
                path: `/pages/orderDetail/orderDetail?orderInfo=${orderInfoStr}&storeName=${encodeURIComponent(this.data.storeName || '')}`
            };
        });
    }
})
